package com.hongyi.serivice.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.hongyi.pojo.User;
import com.hongyi.serivice.UserService;
import com.hongyi.utils.HttpUtils1;
import com.hongyi.vo.ApiResponse;
import com.hongyi.vo.ApiResponseList;
import com.hongyi.vo.UserVo;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @Author: hongyi
 * @CreateTime: 2024-10-22 15:03:00
 */


@Service
@Log4j2
public class UserServiceImpl2 implements UserService {
    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();


    /*@Override
    public List<UserVo> findALl() {
        String host = "http://127.0.0.1:9091/";
        String path = "user/findAll";
        String method = "GET";

        // 创建 ThreadPoolExecutor
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);

        try {
            // 定义一个 Callable 任务
            Callable<List<UserVo>> task = () -> {
                // 发起 HTTP 请求并获取响应体
                HttpResponse response = HttpUtils1.doGet(host, path, method);
                // 处理响应体
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 将响应体转换为字符串
                    String json = EntityUtils.toString(response.getEntity());
                    // 将 JSON 字符串转换为 ApiResponseList 对象
                    ApiResponseList responseList = objectMapper.readValue(json, ApiResponseList.class);
                    List<UserVo> userVO = responseList.getData();
                    return userVO;
                } else {
                    throw new RuntimeException("请求失败，状态码：" + response.getStatusLine().getStatusCode());
                }
            };

            //  提交任务到线程池并获取Future
            Future<List<UserVo>> future = executor.submit(task);
            return future.get(); // 阻塞直到获取结果

        } catch (Exception e) {
            throw new RuntimeException("获取用户信息失败", e); // 抛出更明确的异常
        } finally {
            // 关闭线程池
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }
*/


    @Override
    public List<UserVo> findALl() throws Exception {
        String host = "http://127.0.0.1:9091/";
        String path = "user/findAll";
        String method = "GET";

        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
        List<UserVo> userVOList = new ArrayList<>(); // 用于存储结果

        try {
            // 定义一个 Runnable 任务
            Runnable task = () -> {
                try {
                    HttpResponse response = HttpUtils1.doGet(host, path, method);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        String json = EntityUtils.toString(response.getEntity());
                        ApiResponseList responseList = objectMapper.readValue(json, ApiResponseList.class);
                        synchronized (userVOList) {
                            userVOList.addAll(responseList.getData()); // 更新结果
                        }
                    } else {
                        throw new RuntimeException("请求失败，状态码：" + response.getStatusLine().getStatusCode());
                    }
                } catch (Exception e) {
                    throw new RuntimeException("获取用户信息失败", e);
                }
            };

            // 提交任务到线程池
            executor.submit(task);
            // 关闭线程池
            executor.shutdown();
            executor.awaitTermination(60, TimeUnit.SECONDS); // 等待任务完成

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt();
        }

        return userVOList; // 返回结果
    }

    @Override
    public UserVo getById(Long id) {
        String host = "http://127.0.0.1:9091/";
        String path = "user/" + id;
        String method = "GET";

        // 创建 ThreadPoolExecutor
        //ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(5,
                10,
                10,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10));


        try {
            // 定义一个 Callable 任务
            Callable<UserVo> task = () -> {
                // 发起 HTTP 请求并获取响应体
                HttpResponse response = HttpUtils1.doGet(host, path, method);
                // 处理响应体
                if (response.getStatusLine().getStatusCode() == 200) {
                    // 将响应体转换为字符串
                    String json = EntityUtils.toString(response.getEntity());
                    // 将 JSON 字符串转换为 ApiResponse 对象
                    ApiResponse apiResponse = objectMapper.readValue(json, ApiResponse.class);
                    // 将 ApiResponse 中的数据部分转换为 UserVo 对象
                    UserVo userVo = apiResponse.getData();
                    //返回 UserVo 对象
                    return userVo;
                } else {
                    throw new RuntimeException("请求失败，状态码：" + response.getStatusLine().getStatusCode());
                }
            };

            //  提交任务到线程池并获取Future
            Future<UserVo> future = executor.submit(task);
            return future.get(); // 阻塞直到获取结果

        } catch (Exception e) {
            // 记录错误
            throw new RuntimeException("获取用户信息失败", e);
        } finally {
            // 关闭线程池
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();

            }
        }
    }


    @Override
    public void save(User user) {
        String host = "http://127.0.0.1:9091/";
        String path = "user/insert";
        String method = "POST";

        // 创建 ThreadPoolExecutor
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);

        try {
            // 定义一个 Callable 任务
            Callable<Void> task = () -> {
                Gson gson = new Gson();
                String requestBody = gson.toJson(user);
                HttpResponse response = HttpUtils1.doPost(host, path, method, requestBody);

                if (response.getStatusLine().getStatusCode() == 200) {
                    // System.out.println("保存成功");
                    log.info("保存成功");
                } else {
                    //   System.err.println("保存失败，状态码：" + response.getStatusLine().getStatusCode());
                    log.error("保存失败，状态码：{}", response.getStatusLine().getStatusCode());
                }

                // 处理响应体（可选）
                String jsonResponse = EntityUtils.toString(response.getEntity());
                // System.out.println(jsonResponse);
                log.info("响应体: {}", jsonResponse);
                return null; // Callable 需要返回值，这里返回 null
            };

            // 提交任务到线程池
            Future<Void> future = executor.submit(task);
            future.get(); // 阻塞直到任务完成

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }


    @Override
    public void update(User user) {
        String host = "http://127.0.0.1:9091/";
        String path = "user/update";
        String method = "PUT";

        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);

        try {
            Callable<Void> task = () -> {
                Gson gson = new Gson();
                String requestBody = gson.toJson(user);
                HttpResponse response = HttpUtils1.doPut(host, path, method, requestBody);

                if (response.getStatusLine().getStatusCode() == 200) {
                    //  System.out.println("修改成功");
                    log.info("修改成功");
                } else {
                    //  System.err.println("修改失败，状态码：" + response.getStatusLine().getStatusCode());
                    log.error("修改失败，状态码：{}", response.getStatusLine().getStatusCode());
                }

                String jsonResponse = EntityUtils.toString(response.getEntity());
                //    System.out.println(jsonResponse);
                log.info("响应体: {}", jsonResponse);
                return null;
            };

            Future<Void> future = executor.submit(task);
            future.get();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }

    @Override
    public void delete(Long id) {
        String host = "http://127.0.0.1:9091/";
        String path = "user/delete/" + id;
        String url = host + path;
        String method = "DELETE";

        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);


        try {
            // callable 任务
            Callable<Void> task = () -> {
                HttpResponse response = HttpUtils1.doDelete(host, path, method);

                if (response.getStatusLine().getStatusCode() == 200) {
                    //   System.out.println("删除成功");
                    log.info("删除成功");
                }
                // 处理响应体（可选）
                String jsonResponse = EntityUtils.toString(response.getEntity());
                // System.out.println(jsonResponse);
                log.info("响应体: {}", jsonResponse);
                return null;
            };
            Future<Void> future = executor.submit(task);
            future.get();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }


    @Override
    public List<UserVo> findName(String name) throws Exception {
        //
        // http://127.0.0.1:9091/user/findByName?name=A
        // 构建请求 URL
        String host = "http://127.0.0.1:9091/";
        String path = new URIBuilder("user/findByName2").addParameter("name", name).build().toString();
        String url = host + path;
        String method = "GET";
        // 创建线程池
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        try {
            // 创建 Callable 任务
            Callable<List<UserVo>> task = () -> {
                HttpResponse response = HttpUtils1.doGet(host, path, method);

                // 检查 HTTP 响应状态码
                if (response.getStatusLine().getStatusCode() == 200) { // 如果状态码为 200，表示请求成功
                    // 将响应体转换为字符串
                    String json = EntityUtils.toString(response.getEntity());

                    // 将 JSON 字符串转换为 ApiResponse 对象
                    ApiResponseList apiResponse = objectMapper.readValue(json, ApiResponseList.class);
                    // 从 ApiResponse 中获取 UserVo 对象
                    List<UserVo> userVos = apiResponse.getData();
                    return userVos;
                } else {
                    throw new RuntimeException("请求失败，状态码：" + response.getStatusLine().getStatusCode());
                }
            };

            Future<List<UserVo>> future = executor.submit(task);
            return future.get(); // 等待任务完成并获取结果


        } catch (Exception e) {
            // log.info("获取用户信息失败:{}", e);
            throw new RuntimeException("获取用户信息失败", e); // 抛出更明确的异常
        } finally {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }
    }


    @Override
    public List<UserVo> findUser(User user) throws Exception {
        String host = "http://127.0.0.1:9091/";
        // String path = "user/findUser";

        String path = new URIBuilder("user/findByUserVo")
                .addParameter("name", user.getName())
                .addParameter("email", user.getEmail())
                .build().
                toString();
        String method = "GET";

        // 创建线程池
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);

        // 创建 Callable 任务
        try {
            Callable<List<UserVo>> task = () -> {
                // 发送 GET 请求
                HttpResponse response = HttpUtils1.doGet(host, path, method);

                // 检查 HTTP 响应状态码
                if (response.getStatusLine().getStatusCode() == 200) { // 如果状态码为 200，表示请求成功
                    // 将响应体转换为字符串
                    String json = EntityUtils.toString(response.getEntity());

                    // 将 JSON 字符串转换为 ApiResponse 对象
                    ApiResponseList apiResponse = objectMapper.readValue(json, ApiResponseList.class);
                    // 从 ApiResponse 中获取 UserVo 对象
                    List<UserVo> userVos = apiResponse.getData();
                    return userVos;
                } else {
                    throw new RuntimeException("请求失败，状态码：" + response.getStatusLine().getStatusCode());
                }
            };
            // 提交任务到线程池
            Future<List<UserVo>> future = executor.submit(task);
            return future.get(); // 阻塞直到任务完成并获取结果
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
            }
        }

    }
}
